package com.hmall.search.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hmall.client.ItemClient;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.PageDTO;
import com.hmall.search.dto.ItemDoc;
import com.hmall.search.pojo.RequestParam;
import com.hmall.search.service.SearchService;
import org.apache.http.HttpHost;
import org.checkerframework.checker.units.qual.A;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.lucene.search.function.CombineFunction;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liCuiPing
 * @since 2022/12/9 16:57
 */
@Service
public class SearchServiceImpl implements SearchService {

    //@Autowired
    private RestHighLevelClient client;

    @Autowired
    private ItemClient itemClient;

    /**
     * 保存一条item通过id
     * @param id
     */
    @Override
    public void saveItemByid(Long id) {
        try {
            //查询一条酒店数据,并转为json
            Item item = itemClient.findById(id);
            ItemDoc itemDoc = new ItemDoc(item);
            String jsonString = JSON.toJSONString(itemDoc);

            //创建请求
            IndexRequest request = new IndexRequest("item").id(itemDoc.getId().toString());
            //设置参数
            request.source(jsonString, XContentType.JSON);
            //执行请求
            client.index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过id删除
     * @param id
     */
    @Override
    public void deleteItemByid(Long id) {
        try {
            //创建请求
            DeleteRequest request = new DeleteRequest("item",id.toString());
            //执行请求
            client.delete(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<String> suggestionSearch(String key) {
        restClientStart();
        //创建请求
        SearchRequest request = new SearchRequest("item");
        //设置参数
        request.source().suggest(
                new SuggestBuilder().addSuggestion("suggestItem", //查询名称(自定义)
                        SuggestBuilders.completionSuggestion("suggestion") //创建索引库时自动补全字段的字段名称
                                .prefix(key) //查询'传参'开头的词条
                                .size(10) //相当于mysql的 limit 10
                                .skipDuplicates(true) //重复词条只保留一份
                )
        );
        //执行请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        //解析结果
        //返回字段
        ArrayList<String> resultList = new ArrayList<>();
        Suggest suggest = response.getSuggest();
        CompletionSuggestion suggest1 = suggest.getSuggestion("suggestItem");
        List<CompletionSuggestion.Entry.Option> optionList = suggest1.getOptions();
        for (CompletionSuggestion.Entry.Option option : optionList) {
            String str = option.getText().string();
            resultList.add(str);
        }
        restClientClose();
        return resultList;
    }

    /**
     * se聚合查询 *品牌 *分类
     * @return
     */
    @Override
    public Map<String, List<String>> filter(RequestParam requestParam) {
        restClientStart();

        try {
            //创建请求
            SearchRequest request = new SearchRequest("item");
            //设置查询条件
            buildBaseRequest(requestParam, request);
            //设置聚合参数
            request.source().size(0); //不在结果中包含文档详情

            request.source().aggregation(
                    AggregationBuilders.terms("categoryAgg").field("category").size(50)
            );
            request.source().aggregation(
                    AggregationBuilders.terms("brandAgg").field("brand").size(50)
            );

            //执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            List<String> categoryAgg = fetchAggs(response, "categoryAgg");
            List<String> brandList = fetchAggs(response, "brandAgg");
            //响应
            Map<String, List<String>> map = new HashMap<>();
            map.put("category",categoryAgg);
            map.put("brand",brandList);
            return map;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            restClientClose();
        }
    }

    /**
     * 分页查询过滤关键字并且分页
     * @param requestParam
     * @return
     */
    @Override
    public PageDTO<ItemDoc> listPage(RequestParam requestParam) {
        restClientStart();
        try {
            //分页结果
            PageDTO<ItemDoc> pageResult = new PageDTO<>();
            //创建请求
            SearchRequest request = new SearchRequest("item");
            //设置参数
            buildBaseRequest(requestParam, request);

            //排序
            if( "sold".equals(requestParam.getSortBy()) ){
                request.source().sort("sold", SortOrder.DESC);
            } else if ( "price".equals(requestParam.getSortBy())) {
                request.source().sort("price",SortOrder.ASC);
            }

            //分页
            request.source().from( (requestParam.getPage()-1)*requestParam.getSize() ).size( requestParam.getSize() );

            //高亮
            request.source().highlighter(
                    //new HighlightBuilder().field("name").requireFieldMatch(false)
                    new HighlightBuilder().field("name").requireFieldMatch(true)
            );

            //执行请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析响应
            SearchHits searchHits = response.getHits();
            long total = searchHits.getTotalHits().value;
            pageResult.setTotal(total); //文档总数量

            List<ItemDoc> items = new ArrayList<>();
            SearchHit[] hits = searchHits.getHits();
            for (SearchHit hit : hits) {
                String json = hit.getSourceAsString();
                ItemDoc itemDoc = JSONObject.parseObject(json, ItemDoc.class);
                //高亮
                Map<String, HighlightField> highlightFieldMap = hit.getHighlightFields();
                HighlightField highlightField = highlightFieldMap.get("name");
                if( highlightField!=null && highlightField.getFragments().length>0){
                    String highLightName = highlightField.getFragments()[0].string();
                    System.out.println("高亮处理后de名称: " + highLightName);
                    itemDoc.setName(highLightName);
                }
                items.add(itemDoc);
            }
            pageResult.setList(items); //当前页的酒店数据明细
            Thread.sleep(2000);
            return pageResult;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 关闭es连接
     */
    private void restClientClose()  {
        try {
            client.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 连接es
     */
     void restClientStart() {
        client = new RestHighLevelClient(
                RestClient.builder(HttpHost.create("http://192.168.179.131:9200"))
        );
    }

    /**
     * 解析聚合响应得到聚合出的所有字段名list
     * @param response
     * @param aggName
     * @return
     */
    private List<String> fetchAggs(SearchResponse response, String aggName){
        List<String> list = new ArrayList<>();
        Aggregations aggregations = response.getAggregations();
        Terms brandAgg = aggregations.get(aggName);
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
            list.add(key);
        }
        return list;
    }

    private void buildBaseRequest(RequestParam params, SearchRequest request) {
        //关键字查询
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if( StringUtils.isBlank(params.getKey()) ){
            boolQuery.must( QueryBuilders.matchAllQuery() );
        }else {
            //boolQuery.must( QueryBuilders.matchQuery("all",params.getKey()) );
            boolQuery.must( QueryBuilders.matchQuery("name", params.getKey()) );
        }

        //多条件过滤: 品牌,分类
        if( StringUtils.isNotBlank(params.getBrand()) ){
            boolQuery.filter( QueryBuilders.termQuery("brand", params.getBrand()) );
        }
        if( StringUtils.isNotBlank(params.getCategory()) ){
            boolQuery.filter( QueryBuilders.termQuery("category", params.getCategory()) );
        }
        if( params.getMinPrice()!=null && params.getMaxPrice()!=null ){
            boolQuery.filter(
                    QueryBuilders.rangeQuery("price").gte(params.getMinPrice()).lte(params.getMaxPrice())
            );
        }
        //函数算分查询
            FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(
                    boolQuery, //原始查询
                    new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                            new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                    QueryBuilders.termQuery("isAD", true), //过滤条件(符合条件的文档,重新打分)
                                    ScoreFunctionBuilders.weightFactorFunction(10) //如何打分
                            )
                    }
            ).boostMode(CombineFunction.SUM);//加权规则(新旧得分运算规则)
        //设置整体查询
        request.source().query(functionScoreQueryBuilder);

    }

}